package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.EmployeeQueryObject;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.result.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @RequiredPermission(name = "员工列表",expression = "employee:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){
        PageInfo<Employee> pageResult = employeeService.query(qo);
        model.addAttribute("result",pageResult);
        model.addAttribute("departments",departmentService.listAll());
        return "employee/list";
    }

    @RequiredPermission(name = "员工删除",expression = "employee:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                employeeService.delete(id);
                return new JsonResult(true,"删除成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(true,"删除失败");

    }


    @RequiredPermission(name = "员工添加",expression = "employee:input")
    @RequestMapping("/input")
    public String input(Model model,Long id){
        model.addAttribute("departments",departmentService.listAll());
        model.addAttribute("roles",roleService.listAll());
        if (id != null) {
            model.addAttribute("employee",employeeService.get(id));
        }
        return "employee/input";
    }

    @RequiredPermission(name = "员工添加或修改",expression = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee,Long ids[]){
        if (employee.getId() != null) {
            employeeService.update(employee,ids);
        }else {
            employeeService.save(employee,ids);
        }
        return "redirect:/employee/list.do";
    }
}
